<?php
class Webkul_Marketplacepartner_Model_Productsales extends Mage_Core_Model_Abstract
{
	 public function _construct() {
        parent::_construct();
        $this->_init('marketplacepartner/productsales');
    }
	public function getProductSalesDetailById($productId){
		$data = array();
        if($productId > 0){
           $collection = Mage::getResourceModel('marketplacepartner/productsales_collection');
           $collection->getSelect()->where('mageproid ='.$productId);
			$i=0;
			foreach ($collection as $record) {
				$data[$i]=array(
							'magequantity'=>$record->getmagequantity(),
							'actualparterprocost'=>$record->getactualparterprocost()
						);
				$i++;
			}
			return $data;
		}
	}
	public function getProductSalesCalculation($order){
	
	$percent = Mage::getStoreConfig('partners/partners_options/percent');
	$lastOrderId=$order->getId();
		foreach ($order->getAllItems() as $item){
				$temp=$item->getProductOptions();
				$price=$item->getPrice();
				$collection12 = Mage::getModel('marketplacepartner/userdata')->getCollection();
				$collection12->getSelect()->where('mageproductid ='.$item->getProductId());
				foreach($collection12 as $selid){
				$seller_id=$selid->getuserid();
				}
		if($seller_id==''){$seller_id=0;}
		$write = Mage::getSingleton('core/resource')->getConnection('core_write');
		$mysqlprefix = Mage::getConfig()->getTablePrefix();//code for mysql prefix
		
		
		$collection = Mage::getModel('marketplacepartner/userdata')->getCollection();
		$collection->getSelect()->where('mageproductid ='.$item->getProductId());
		foreach($collection as $row){
		$userid=$row->getuserid();
		
			
			$collection1 = Mage::getResourceModel('marketplacepartner/sellerpayment_collection');
						$collection1->getSelect()->where('mageuserid ='.$userid);
						$totalamount=$item->getQtyToInvoice()*$item->getPrice();
						if(count($collection1)!=0){
						foreach($collection1 as $rowdatasale) {
						if($rowdatasale->getcommision()>0){$commision=($totalamount*$rowdatasale->getcommision())/100;}
						else{$commision=($totalamount*$percent)/100;}
					}
					}
					else{
					$commision=($totalamount*20)/100;
					}
					}
					$actparterprocost=$totalamount-$commision;
			// end changes made here to set percentage commission for per partner else working correct for common %
			$collectionsave=Mage::getModel('marketplacepartner/productsales');
			$collectionsave->setmageproid($item->getProductId());
			$collectionsave->setmageorderid($lastOrderId);
			$collectionsave->setmagerealorderid($order->getIncrementId());
			$collectionsave->setmagequantity($item->getQtyToInvoice());
			$collectionsave->setmageproownerid($seller_id);
			$collectionsave->setcpproid(0);
			$collectionsave->setmagebuyerid(Mage::getSingleton('customer/session')->getCustomer()->getId());
			$collectionsave->setmageproprice($item->getPrice());
			$collectionsave->setmageproname($item->getName());
			if($totalamount!=0){
			$collectionsave->settotalamount($totalamount);
			}
			else{
			$collectionsave->settotalamount($price);
			}
			$collectionsave->settotalcommision($commision);
			$collectionsave->setactualparterprocost($actparterprocost);
			$collectionsave->setcleared_at(date('Y-m-d H:i:s'));
			$collectionsave->save();
				$collectionverifyread = Mage::getResourceModel('marketplacepartner/sellerpayment_collection');
				$collectionverifyread->getSelect()->where('mageuserid ='.$seller_id);
							if(count($collectionverifyread)>=1){
							foreach($collectionverifyread as $verifyrow){
								$totalsale=$verifyrow->gettotalsale()+$actparterprocost;
								$totalremain=$verifyrow->getamountremain()+$actparterprocost;
								$write = Mage::getSingleton('core/resource')->getConnection('core_write');
								$mysqlprefix = Mage::getConfig()->getTablePrefix();//code for mysql prefix
								$write->query("update ".$mysqlprefix."marketplacepartner_entity_saleperpartner set totalsale ='$totalsale',amountremain='$totalremain' where mageuserid ='".$seller_id."'");
								
							}
							
							
					}
				else{
				
							$collectionf=Mage::getModel('marketplacepartner/sellerpayment');
							$collectionf->setmageuserid($seller_id);
							$collectionf->settotalsale($totalamount);
							$collectionf->setamountremain($actparterprocost);
							$collectionf->save();
							
				}
				
				// end code to cross check that entry is on table or not as well we will update the saletable for per partner
			$email = Mage::getModel('customer/customer')->load($seller_id)->getemail();
			$cname = Mage::getModel('customer/customer')->load($seller_id)->getName();
			$ee = Mage::getModel('core/email_template')->loadDefault('customerpartner_email');
			$aa = array();
			$aa['myvar1'] =$order->getIncrementId();
			$aa['myvar2'] = $cname;
			$aa['myvar3'] = $item->getQtyToInvoice();
			$aa['myvar4'] = $item->getPrice();
			$aa['myvar5'] = $totalamount;
			$aa['myvar6'] = $item->getName();
			$processedTemplate = $ee->getProcessedTemplate($aa);
			$ee->setSenderName('Sales Department');
			$ee->setSenderEmail('sales@store.com');
			$ee->send($email,$cname, $aa); 
			
		}
		}
	public function getMonthlysale($userid){
	$db = Mage::getSingleton('core/resource')->getConnection('core_read');
		// Now $db is an instance of Zend_Db_Adapter_Abstract
	$data=array();
	
		for($i=1;$i<=12;$i++){
		$date1="2013-".$i."-01 00:00:00";
		$date2="2013-".$i."-31 23:59:59";
		
		$collection = Mage::getResourceModel('marketplacepartner/productsales_collection');
		$collection->getSelect()->where('mageproownerid ='.$userid.' AND cleared_at BETWEEN "'.$date1.'" AND "'.$date2.'"');
		     $sum=array();
		     $temp=0;
			foreach ($collection as $record) {
			$temp=$temp+$record->getactualparterprocost();
			}
			$data[$i]=$temp;
			
		}
		return json_encode($data);	
	}
	public function getnumroww($userid,$p){
	$collection = Mage::getResourceModel('marketplacepartner/productsales_collection');
	$collection->getSelect()->where('mageproownerid ='.$userid);
	$total_results=count($collection);
    return ceil($total_results / 10);	
	}
	public function getallOrderdetails($userid,$p){
	$collection = Mage::getModel('marketplacepartner/productsales')->getCollection();
			//$collection->getSelect()->where('mageproownerid ='.$userid)->order("autoid DESC");
			 $collection->addFieldToFilter('mageproownerid',array('eq'=>$userid));
			 $collection->setCurPage($p);
			 $collection->setPageSize(10);
		     $userorder=array();
			 $gropoid=array();
			 $groporderid=array();
			 $productname=array();
		     $i=0;
			foreach ($collection as $record) {
			$i++;
				if($i<=10){
				
						if($record->getmagerealorderid()==$gropoid[$i-1]){
							$i--;
							$productid=$productid.",".$record->getmageproid();
							$productname=$productname.",".$record->getmageproname()." X ".$record->getmagequantity();
							$pprice=$pprice+$record->getactualparterprocost();
							$userorder[$i]=array('mageproid'=>$productid,
													'mageorderid'=>$record->getmageorderid(),
													'magerealorderid'=>$record->getmagerealorderid(),
													'mageproname'=>$productname,
													'actualparterprocost'=>$pprice,
													'cleared_at'=>$record->getcleared_at()
													);			
						}
						else{
							$productname=$record->getmageproname()." X ".$record->getmagequantity();
							$productid=$record->getmageproid();
							$pprice=$record->getactualparterprocost();
							$groporderid[$i]=$record->getmageorderid();
							$gropoid[$i]=$record->getmagerealorderid();
							$userorder[$i]=array('mageproid'=>$record->getmageproid(),
												'mageorderid'=>$record->getmageorderid(),
												'magerealorderid'=>$record->getmagerealorderid(),
												'mageproname'=>$productname,
												'actualparterprocost'=>$pprice,
												'cleared_at'=>$record->getcleared_at()
												);			
							}	
					}
			}
			
		
		return $userorder;	
	}
	public function getOrderdetails($userid){
	$collection = Mage::getResourceModel('marketplacepartner/productsales_collection');
			$collection->getSelect()->where('mageproownerid ='.$userid)->order("autoid DESC");
		     $userorder=array();
			 $gropoid=array();
			 $groporderid=array();
			 $productname=array();
		     $i=0;
			
			foreach ($collection as $record) {
			$i++;
				if($i<=5){
				
						if($record->getmagerealorderid()==$gropoid[$i-1]){
							$i--;
							$productid=$productid.",".$record->getmageproid();
							$productname=$productname.",".$record->getmageproname()." X ".$record->getmagequantity();
							$pprice=$pprice+$record->getactualparterprocost();
							$userorder[$i]=array('mageproid'=>$productid,
													'mageorderid'=>$record->getmageorderid(),
													'magerealorderid'=>$record->getmagerealorderid(),
													'mageproname'=>$productname,
													'actualparterprocost'=>$pprice,
													'cleared_at'=>$record->getcleared_at()
													);			
						}
						else{
							$productname=$record->getmageproname()." X ".$record->getmagequantity();
							$productid=$record->getmageproid();
							$pprice=$record->getactualparterprocost();
							$groporderid[$i]=$record->getmageorderid();
							$gropoid[$i]=$record->getmagerealorderid();
							$userorder[$i]=array('mageproid'=>$record->getmageproid(),
												'mageorderid'=>$record->getmageorderid(),
												'magerealorderid'=>$record->getmagerealorderid(),
												'mageproname'=>$productname,
												'actualparterprocost'=>$pprice,
												'cleared_at'=>$record->getcleared_at()
												);			
							}	
					}
			}
			
		
		return $userorder;	
	}
	
	public function getDateDetail(){ 
		     $session = Mage::getSingleton('customer/session'); 
			$cidvar = $session->getId();
          $collection1 = Mage::getModel('marketplacepartner/productsales')->getCollection()
          								->addFieldToFilter('mageproownerid',array('eq'=>$cidvar));
		  $collection2= Mage::getModel('marketplacepartner/productsales')->getCollection()
          								->addFieldToFilter('mageproownerid',array('eq'=>$cidvar));
		  $collection3 = Mage::getModel('marketplacepartner/productsales')->getCollection()
          								->addFieldToFilter('mageproownerid',array('eq'=>$cidvar));
		 /* $date=date("y-m-d");
		  $a=explode('-',$date);
		  $data1=array();
          
		   $temp="20".$a[0]."%";
		   $tempdate="%-".$a[2]."%";
		   $tempmonth="%-".$a[1]."-%";*/
		    $first_day_of_week = date('Y-m-d', strtotime('Last Monday', time()));
			$last_day_of_week = date('Y-m-d', strtotime('Next Sunday', time()));
		   $month=$collection1->addFieldToFilter('cleared_at', array('datetime' => true,'from' =>  date('Y-m').'-01 00:00:00','to' =>  date('Y-m').'-31 23:59:59'));
		   $week=$collection2->addFieldToFilter('cleared_at', array('datetime' => true,'from' =>  $first_day_of_week.' 00:00:00','to' =>  $last_day_of_week.' 23:59:59'));
		   $day=$collection3->addFieldToFilter('cleared_at', array('datetime' => true,'from' =>  date('Y-m-d').' 00:00:00','to' =>  date('Y-m-d').' 23:59:59'));
		   //print_r(count($week));

		   //$collection->getSelect()->where('cleared_at LIKE "'.$temp.'"');
		   //$collection->getSelect()->where('cleared_at LIKE "'.$temp.'"');
		   $sale=0;
		  
			foreach($collection as $record) {
			
				$sale=$sale+$record->gettotalamount();
				}
			$data1['year']=$sale;
			//$collection1->getSelect()->where('cleared_at LIKE "'.$tempdate.'"');
		  	$sale1=0;
			foreach($day as $record1) {
				$sale1=$sale1+$record1->gettotalamount();
			}
			$data1['day']=$sale1;
			//$collection2->getSelect()->where('cleared_at LIKE "'.$tempmonth.'"');
		  	$sale2=0;
			foreach($month as $record2) {
				$sale2=$sale2+$record2->gettotalamount();
			}
			$data1['month']=$sale2;
			//$previous=date('y-m-d',strtotime( "last sunday" ));	
			//$next=date('y-m-d',strtotime( "next sunday" ));
			
			//$collection3->getSelect()->where('cleared_at BETWEEN "'.$previous.'" AND "'.$next.'"');
		  	$sale3=0;
			foreach($week as $record3) {
				$sale3=$sale3+$record3->gettotalamount();
			}
			$data1['week']=$sale3;

			//print_r($data1);
			return $data1;
		
	}
	
	public function getSimplePostAction($data,$customerId,$id){
	
	print_r($data);
	}
	
}